import { createApp } from "vue";
import type { App as VueApp } from "vue";
import App from "./App";
import Router from "@application/router";
import { initProjectLogics } from '@application/logics'
import { showWindow, windowLoad } from "@application/ipc/window";
import ElementPlus from 'element-plus'

import './assets/styles/global.css';
import 'element-plus/dist/index.css'

class InitApp {
  private _APP: Nullable<VueApp<Element>> = null ; 
  constructor(app:typeof App) {
    this.elcListener(app);
  }

  //桌面端ipc监听
  elcListener(app: typeof App) {
    
    windowLoad((_, customize) => {
      //将customize存进window中
      window.customize = customize;

      //显示window
      showWindow(customize?.id);

      this._APP = createApp(app);

      this.init();

    });
  }

  //初始化
  init() {
    try {
      this.useAppPlugin();
      this.buildAppHandle();
      this.start();
    } catch (err: any) {
      throw new Error(err.message ?? err);
    }
  }
  useAppPlugin() {
    //挂载官方插件
    try {
      [
        { name: "router", value: Router(window.customize.route) },
        { name: 'elementPlus', value: ElementPlus }
      ]
      .forEach((plugin) => {
        this._APP?.use(plugin.value);
      });
    } catch {
      throw new Error("挂载官方插件失败");
    }
  }
  buildAppHandle() {
    try {
      // 项目启动逻辑
      initProjectLogics(this._APP);

    } catch (err: any) {
      throw new Error(err.message || err);
    }
  }
  start() {
    //挂载页面
    try {
      this._APP?.mount("#root");
    } catch (err: any) {
      throw new Error("挂载页面失败");
    }
  }
}

new InitApp(App);
